import sys
import time
import re
import configparser
import pyautogui
import pyperclip
import win32con
import win32gui
from PyQt6.QtCore import (
    QCoreApplication,
    Qt,
    QRect,
    QSize,
    QThread,
    pyqtSignal,
    QMutex,
    QWaitCondition,
)
from PyQt6.QtGui import QIcon, QKeySequence, QShortcut
from PyQt6.QtWidgets import (
    QApplication,
    QPlainTextEdit,
    QRadioButton,
    QPushButton,
    QLabel,
    QTextBrowser,
    QVBoxLayout,
    QWidget,
    QComboBox,
    QCheckBox,
    QSpinBox,
)
from system_hotkey import SystemHotkey

conf = configparser.ConfigParser()
conf.read("data.ini", encoding="utf-8")
pyautogui.FAILSAFE = True
# 定义石头和装备位置
stones = {
    "coordinate": conf["coordinate"]["coordinate_1"].split(","),
    "metamorphosisStone": conf["coordinate"]["metamorphosisStone"].split(","),
    "amplifierStone": conf["coordinate"]["amplifierStone"].split(","),
    "transwidgetationStone": conf["coordinate"]["transwidgetationStone"].split(","),
    "reforgedStone": conf["coordinate"]["reforgedStone"].split(","),
    "regalStone": conf["coordinate"]["regalStone"].split(","),
}


class Worker(QThread):
    finished = pyqtSignal()  # 任务完成的信号
    progress = pyqtSignal(str)  # 进度更新的信号

    def __init__(
        self,
        affix=None,
        secondaryAffix=None,
        radioButton_bool=False,
        radioButton_bool_2=False,
    ):
        super().__init__()
        self.is_running = True  # 线程是否运行的标志
        self.is_paused = False  # 线程是否暂停的标志
        self.mutex = QMutex()  # 互斥锁，用于线程同步
        self.condition = QWaitCondition()  # 条件变量，用于线程暂停和恢复
        self.affix = affix  # 词缀1
        self.secondaryAffix = secondaryAffix  # 词缀2
        self.radioButton_bool = radioButton_bool
        self.radioButton_bool_2 = radioButton_bool_2

    def run(self):

        while True:
            self.mutex.lock()  # 在检查运行状态和暂停状态之前获取互斥锁
            if not self.is_running:
                self.mutex.unlock()  # 在完成之前释放互斥锁
                break
            if self.is_paused:
                self.condition.wait(self.mutex)  # 等待条件被通知，线程暂停
                self.is_paused = False  # 重置暂停标志
            self.mutex.unlock()  # 在发射进度信号之前释放互斥锁
            self.gettingInwidgetation()
            ret_data = self.data_li()
            self.progress.emit(ret_data)  # 发射进度信号
            if ret_data == "装备完成了":
                break
        self.finished.emit()  # 发射任务完成信号

    def stop(self):
        self.mutex.lock()
        self.is_running = False  # 停止线程运行
        self.condition.wakeAll()  # 唤醒所有等待的线程
        self.mutex.unlock()

    def pause(self):
        self.mutex.lock()
        self.is_paused = True  # 暂停线程运行
        self.mutex.unlock()

    def resume(self):
        self.mutex.lock()
        self.condition.wakeAll()  # 唤醒所有等待的线程，恢复线程执行
        self.mutex.unlock()

    def data_li(self):
        data = pyperclip.paste().replace("\r", "")
        rarity = re.findall("稀 有 度: (.*)", data)
        # rarity_match = re.search(r"稀 有 度:\s*(\w+)", data)

        # rarity = RE_FINDALL  # 匹配 装备的稀有度
        # 使用正则表达式匹配并计数
        rarity2 = re.findall(r"\{ (前缀|后缀)属性", data)
        print(rarity, rarity2)
        if rarity:
            rarity = rarity[0]
            if rarity == "普通":
                pyautogui.moveTo(stones["metamorphosisStone"], duration=0.1)
                pyautogui.click(button="right")
                pyautogui.moveTo(stones["coordinate"], duration=0.1)
                pyautogui.click()
                return "蜕变石"

            elif rarity == "魔法":
                if len(rarity2) == 1:
                    print(stones["amplifierStone"])
                    pyautogui.moveTo(stones["amplifierStone"], duration=0.1)
                    pyautogui.click(button="right")
                    pyautogui.moveTo(stones["coordinate"], duration=0.1)
                    pyautogui.click()
                    return "增幅石"
                elif len(rarity2) == 2:
                    if self.affix != "" and self.secondaryAffix != "":
                        if self.affix in data or self.secondaryAffix in data:
                            if self.radioButton_bool_2:
                                pyautogui.moveTo(stones["regalStone"], duration=0.1)
                                pyautogui.click(button="right")
                                pyautogui.moveTo(stones["coordinate"], duration=0.1)
                                pyautogui.click()
                                return "富豪石"
                            return "装备完成了"
                        pyautogui.moveTo(stones["transwidgetationStone"], duration=0.1)
                        pyautogui.click(button="right")
                        pyautogui.moveTo(stones["coordinate"], duration=0.1)
                        pyautogui.click()
                        return "改造石"
                    else:
                        raise Exception("条件不可以为空")
            elif rarity == "稀有":
                if len(rarity2) >= 3:

                    if self.affix in data and self.secondaryAffix in data:
                        # win32clipboard.EmptyClipboard()
                        return "装备完成了"
                    elif not self.radioButton_bool:
                        if self.affix in data or self.secondaryAffix in data:
                            return "装备完成了"
                    else:
                        pyautogui.moveTo(stones["reforgedStone"], duration=0.1)
                        pyautogui.click(button="right")
                        pyautogui.moveTo(stones["coordinate"], duration=0.1)
                        pyautogui.click()
                        return "重铸石"
        else:

            time.sleep(1)
            win = win32gui.FindWindow("POEWindowClass", None)
            # 将窗口调到前台
            win32gui.SetForegroundWindow(win)
            win32gui.ShowWindow(win, win32con.SW_SHOW)
            return "没有数据"

    def gettingInwidgetation(self):
        pyautogui.moveTo(stones["coordinate"], duration=0.1)
        time.sleep(0.2)
        pyautogui.hotkey("alt", "ctrl", "c")
        self.progress.emit("获取数据")  # 发射进度信号


class Ui_widget(object):
    def __init__(self) -> None:
        self.worker = Worker()
        self.worker.finished.connect(self.thread_finished)
        self.worker.progress.connect(self.update_progress)

    def setupUi(self, widget):
        if not widget.objectName():
            widget.setObjectName("widget")
        widget.resize(424, 306)
        icon = QIcon()
        icon.addFile("22.png", QSize(), QIcon.Mode.Normal, QIcon.State.Off)
        widget.setWindowIcon(icon)
        self.label = QLabel(widget)
        self.label.setObjectName("label")
        self.label.setGeometry(40, 50, 71, 31)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.plainTextEdit = QPlainTextEdit(widget)
        self.plainTextEdit.setObjectName("plainTextEdit")
        self.plainTextEdit.setGeometry(120, 50, 181, 31)
        self.plainTextEdit.setVerticalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff
        )
        self.plainTextEdit.setHorizontalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff
        )
        self.label_2 = QLabel(widget)
        self.label_2.setObjectName("label_2")
        self.label_2.setGeometry(40, 100, 71, 31)
        self.label_2.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.plainTextEdit_2 = QPlainTextEdit(widget)
        self.plainTextEdit_2.setObjectName("plainTextEdit_2")
        self.plainTextEdit_2.setGeometry(120, 100, 181, 31)
        self.plainTextEdit_2.setVerticalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff
        )
        self.plainTextEdit_2.setHorizontalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff
        )
        self.textBrowser = QTextBrowser(widget)  # 使用 QTextBrowser 创建 textBrowser
        self.textBrowser.setObjectName("textBrowser")  # 设置对象名称
        self.textBrowser.setGeometry(50, 170, 341, 121)  # 设置位置和大小
        self.textBrowser.setReadOnly(True)  # 设置为只读
        self.pushButton = QPushButton(widget)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setGeometry(290, 140, 80, 25)
        # 创建全局快捷键，将其绑定到按钮的槽函数
        self.hk_start = SystemHotkey()
        self.hk_start.register(("f2",), callback=lambda x: self.toggle_thread())

        self.checkBox = QCheckBox(widget)
        self.checkBox.setObjectName("checkBox")
        self.checkBox.setGeometry(50, 140, 95, 19)

        self.checkBox_2 = QCheckBox(widget)
        self.checkBox_2.setObjectName("checkBox_2")
        self.checkBox_2.setGeometry(170, 140, 95, 19)

        self.spinBox = QSpinBox(widget)
        self.spinBox.setObjectName("spinBox")
        self.spinBox.setGeometry(QRect(310, 50, 42, 31))
        self.spinBox_2 = QSpinBox(widget)
        self.spinBox_2.setObjectName("spinBox_2")
        self.spinBox_2.setGeometry(QRect(360, 50, 42, 31))
        self.spinBox_3 = QSpinBox(widget)
        self.spinBox_3.setObjectName("spinBox_3")
        self.spinBox_3.setGeometry(QRect(310, 100, 42, 31))
        self.spinBox_4 = QSpinBox(widget)
        self.spinBox_4.setObjectName("spinBox_4")
        self.spinBox_4.setGeometry(QRect(360, 100, 42, 31))
        self.retranslateUi(widget)
        self.pushButton.clicked.connect(self.toggle_thread)

    def retranslateUi(self, widget):
        widget.setWindowTitle(QCoreApplication.translate("widget", "自动筛选--清安出品", None))
        self.label.setText("可选词汇一")
        self.label_2.setText("可选词汇二")
        self.pushButton.setText("开始运行(F2)")
        self.checkBox.setText("多条词汇")
        self.checkBox_2.setText("是否富豪")

    def toggle_thread(self):
        # 获取两个 plainTextEdit 的文本内容
        affix_text = self.plainTextEdit.toPlainText()
        secondary_affix_text = self.plainTextEdit_2.toPlainText()
        radioButton_bool = self.checkBox.isChecked()
        radioButton_bool_2 = self.checkBox_2.isChecked()

        assert affix_text or secondary_affix_text

        # 更新 Worker 对象的 affix 和 secondaryAffix
        self.worker.affix = affix_text
        self.worker.secondaryAffix = secondary_affix_text
        self.worker.radioButton_bool = radioButton_bool
        self.worker.radioButton_bool_2 = radioButton_bool_2
        if not self.worker.isRunning():
            print("开始运行", radioButton_bool)
            self.pushButton.setText("暂停")
            self.worker.start()
        else:
            if self.worker.is_paused:
                print("暂停")
                self.pushButton.setText("暂停")

                self.worker.resume()  # 继续线程的执行
            else:
                print("继续")
                self.pushButton.setText("继续")
                self.worker.pause()  # 暂停线程的执行

    def thread_finished(self):
        # self.pushButton.setEnabled(True)
        self.pushButton.setText("开始运行(F2)")

    def update_progress(self, progress):
        self.textBrowser.append(f"当前进度: {progress}")


if __name__ == "__main__":
    app = QApplication([])
    widget = QWidget()
    ui = Ui_widget()
    ui.setupUi(widget)
    widget.show()
    app.exec()
